package com.foreveross.crawl.workers.listener;

import org.apache.log4j.Logger;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.JobListener;
import org.quartz.Scheduler;

import com.foreveross.GlobalMapOperatorBeta1;
import com.foreveross.crawl.CrawlContext;
import com.foreveross.crawl.common.em.TaskState;
import com.foreveross.crawl.common.exception.BusinessException;
import com.foreveross.crawl.common.exception.TaskStateException;
import com.foreveross.ehcache.CacheUtil;
import com.foreveross.ehcache.TaskCacheVO;
import com.foreveross.taskservice.common.bean.TaskModel;
/**
 * 对抓取工作worker的监听
 * @author Administrator
 *
 */
public class DefaultCrawlWorkerListenerBeta1 implements JobListener {
	private static Logger logger = Logger.getLogger(DefaultCrawlWorkerListenerBeta1.class);
	public static final String START_TIME="START_TIME";
	@Override
	public String getName() {
		return this.getClass().getName();
	}
	/**
	 * job执行前
	 */
	@Override
	public void jobToBeExecuted(JobExecutionContext context) {
		TaskModel task = (TaskModel)context.getJobDetail().getJobDataMap().get(CrawlContext.CRAWL_TASK);
		this.updateTaskState(task, TaskState.DOING.getType());
		Scheduler scheduler = context.getScheduler();
		try {
			GlobalMapOperatorBeta1.putTaskIdSchedulerMap(task.getId(), scheduler);
			context.getJobDetail().getJobDataMap().put(START_TIME, System.currentTimeMillis());
			GlobalMapOperatorBeta1.updateTaskStartDate(task.getChannel().getId(), task.getId());
			GlobalMapOperatorBeta1.updateTaskDoingNumber(task.getChannel().getId());
		} catch (TaskStateException e) {
			logger.error("更新任务开始时间异常!");
		} catch (BusinessException e) {
			logger.error("更新正在做的任务发生异常");
		}
		logger.info(String.format("开始执行抓取：[%s], 从[%s(%s)]至[%s(%s)], 日期[%s]",
				task.getId(), task.getFromCityName(),task.getFromCity(),task.getToCityName(),task.getToCity(), task.getFlightDate()));
	}

	/**
	 * （Job执行被trigger拒接） 来自官方解释
	 */
	@Override
	public void jobExecutionVetoed(JobExecutionContext context) {
		TaskModel task = (TaskModel)context.getJobDetail().getJobDataMap().get(CrawlContext.CRAWL_TASK);
		this.updateTaskState(task, TaskState.EXCEPTION.getType());
		Scheduler scheduler = context.getScheduler();
		GlobalMapOperatorBeta1.putTaskIdSchedulerMap(task.getId(), scheduler);
	}
	/**
	 * job执行完毕之后
	 */
	@Override
	public void jobWasExecuted(JobExecutionContext context,
			JobExecutionException jobException) {
//		TaskGroup g=(TaskGroup) context.getJobDetail().getJobDataMap().get(CrawlContext.CRAWL_TASK_CHANNEL_GROUP);
		long channelId= context.getJobDetail().getJobDataMap().getLong(CrawlContext.CRAWL_CHANNEL_ID);
		TaskModel task = (TaskModel)context.getJobDetail().getJobDataMap().get(CrawlContext.CRAWL_TASK);

		try {
			long excuteTime = System.currentTimeMillis()-context.getJobDetail().getJobDataMap().getLong(START_TIME);
			GlobalMapOperatorBeta1.updateTaskEndDateAndExcuteTime(channelId, task.getId(), excuteTime);
//			Scheduler scheduler = context.getScheduler();
//			List list = scheduler.getCurrentlyExecutingJobs();
//			String[] groupNames = scheduler.getJobGroupNames();
//			for(String groupName : groupNames){
//				String[] jobNames = scheduler.getJobNames(groupName);
//				System.out.println(jobNames);
//			}
//			Set set = scheduler.getPausedTriggerGroups();
//			GlobalMapOperator.putTaskIdSchedulerMap(task.getId(), scheduler);
			logger.info(String.format("渠道[%s] 常规任务执行完毕！任务耗时[%s]毫秒", channelId,
					excuteTime));
		} catch (Exception e) {
			logger.error(e);
		}
	}

	/**
	 * 更新任务状态
	 * @param key 任务ID
	 * @param state 状态
	 */
	private void updateTaskState(String key,String state){
		Object obj = CacheUtil.getStringValueInCache(key);
		if(obj != null){
			TaskCacheVO vo = (TaskCacheVO)obj;
			vo.setTaskState(state);
			CacheUtil.putStringValueToCache(key, vo);
		}
	}
	
	private void updateTaskState(TaskModel task,String state){
		try {
			GlobalMapOperatorBeta1.updateTaskState(task.getChannel().getId(), task.getId(), state);
		} catch (Exception e) {
			logger.error(e.toString());
		}
	}
	
}
